package com.ruoyi.project.system.leaverequest.service.impl;

import java.util.*;

import com.ruoyi.project.system.drivers.domain.VeDrivers;
import com.ruoyi.project.system.drivers.mapper.VeDriversMapper;
import com.ruoyi.project.system.leaverequest.vo.TaskCommentVo;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;


import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.system.leaverequest.mapper.VeLeaverequestMapper;
import com.ruoyi.project.system.leaverequest.domain.VeLeaverequest;
import com.ruoyi.project.system.leaverequest.service.IVeLeaverequestService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-06
 */
@Service
public class VeLeaverequestServiceImpl implements IVeLeaverequestService 
{
    @Autowired
    private VeLeaverequestMapper veLeaverequestMapper;

    @Autowired
    private VeDriversMapper veDriversMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IUserService userService;
    @Autowired
    private HistoryService historyService;


    /**
     * 查询【请填写功能名称】
     * 
     * @param EmployeeID 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public VeLeaverequest selectVeLeaverequestByEmployeeID(Long EmployeeID)
    {
        return veLeaverequestMapper.selectVeLeaverequestByEmployeeID(EmployeeID);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param veLeaverequest 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<VeLeaverequest> selectVeLeaverequestList(VeLeaverequest veLeaverequest)
    {
        return veLeaverequestMapper.selectVeLeaverequestList(veLeaverequest);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param veLeaverequest 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertVeLeaverequest(VeLeaverequest veLeaverequest)
    {
        return veLeaverequestMapper.insertVeLeaverequest(veLeaverequest);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param veLeaverequest 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateVeLeaverequest(VeLeaverequest veLeaverequest)
    {
        return veLeaverequestMapper.updateVeLeaverequest(veLeaverequest);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param EmployeeIDs 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteVeLeaverequestByEmployeeIDs(String EmployeeIDs)
    {
        return veLeaverequestMapper.deleteVeLeaverequestByEmployeeIDs(Convert.toStrArray(EmployeeIDs));
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param EmployeeID 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteVeLeaverequestByEmployeeID(Long EmployeeID)
    {
        return veLeaverequestMapper.deleteVeLeaverequestByEmployeeID(EmployeeID);
    }






    @Override
    public List<TaskCommentVo> getTaskCommentList(Long flowInstantId) {
        List<TaskCommentVo> taskCommentVoList=new ArrayList<>();

        List<Comment> list = new ArrayList();

        //从历史批注中取数据
        list = taskService.getProcessInstanceComments(""+flowInstantId);

        for (Comment com : list) {
            TaskCommentVo taskCommentVo=new TaskCommentVo();
            taskCommentVo.setMessage(com.getFullMessage());

            User user=userService.selectUserById(Long.parseLong(com.getUserId()));
            taskCommentVo.setUserName(user.getUserName());


            //从历史任务取数据
            List<HistoricTaskInstance> hist= historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(""+flowInstantId)
                    .taskId(com.getTaskId())
                    .list();
            if(hist!=null&&hist.size()>0){
                HistoricTaskInstance historicTaskInstance=hist.get(0);
                taskCommentVo.setTaskKeyId(historicTaskInstance.getTaskDefinitionKey());
                taskCommentVo.setTaskName(historicTaskInstance.getName());
            }
            taskCommentVoList.add(taskCommentVo);
        }


        //排序
        List<TaskCommentVo> taskCommentVoListSort=new ArrayList<>();
        for(int i= taskCommentVoList.size()-1;i>=0;i--)
        {   TaskCommentVo temp=taskCommentVoList.get(i);
            taskCommentVoListSort.add(temp);
        }
        return taskCommentVoListSort;
    }


    @Transactional
    @Override
    public void completeTask(Long flowInstantId, Integer agree,Long userId,String comment,Long id) {
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .processInstanceId("" + flowInstantId)
                .list();
        VeDrivers veDrivers= veDriversMapper.selectVeDriversByDriverID(id);
        // 遍历任务列表
        Map<String, Object> params = new HashMap<String, Object>();
        if (list != null && list.size() > 0) {
            for (Task task : list) {

                if (task.getName().equals("请假申请")) {
                    params.put("inputUser2", 3);
                    veDrivers.setStatus(2);
                } else if (task.getName().equals("部门负责人")) {
                    if (agree == 1)
                        params.put("inputUser3", 2);
                    else
                       veDrivers.setStatus(1);

                    params.put("pass", agree);
                }
                else if(task.getName().equals("总经理")){
                    if(agree==1)
                        params.put("inputUser4",1);
                    else
                        veDrivers.setStatus(1);


                    params.put("pass", agree);
                }


                else {
                    params.put("pass", agree);
                    if (agree==1)
                       veDrivers.setStatus(3);
                    else//状态(0-未提交，1-打回，2-审核中，3-已完成）
                       veDrivers.setStatus(1);
                }
               veDriversMapper.updateVeDrivers(veDrivers);
                Authentication.setAuthenticatedUserId(userId.toString());

                // 添加批注
                taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
                // taskId：任务id
                taskService.complete(task.getId(), params);
            }
        }
    }




    @Override
    public List<VeDrivers> finishTask(Long userId) {

        List<VeDrivers> listFinishTeacher=new ArrayList<>();

        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(userId.toString())
                .processFinished()
                .list();
        if(list!=null&&list.size()>0){
            for(HistoricTaskInstance temp:list){
                Long flowInstanceId= Long.parseLong(temp.getProcessInstanceId());
               VeDrivers veDrivers=veDriversMapper.selectWorkFlowId(flowInstanceId);
                listFinishTeacher.add(veDrivers);

            }
        }
        List<VeDrivers> listFinishTeacher1 = new ArrayList<>(new HashSet<>(listFinishTeacher));
        listFinishTeacher1.removeIf(item -> item == null);

        return listFinishTeacher1;
    }

    @Transactional
    @Override
    public List<VeDrivers> noFinishTask(Long userId) {

        List<VeDrivers> listTeacher = new ArrayList<VeDrivers>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee("" + userId)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                //根据流程id查询老师mapper的方法
                VeDrivers veDrivers = veDriversMapper.selectWorkFlowId(flowInstanceId);
                listTeacher.add(veDrivers);
            }
        }

        return listTeacher;
    }


}
